#define _XOPEN_SOURCE
#include<head.h>
#include "client_puts_file.h"
#include "client_gets_file.h"

int passwdCheck(int peerfd)
{
    char recvbuff[1024] = {0};
    char sendbuff[1024] = {0};
    train_t train;
    memset(&train, 0, sizeof(train));
    /*----输入1或0选择注册还是登陆----*/
    printf("----注册请输0，登陆请输1----\n");
    read(STDIN_FILENO, sendbuff, sizeof(sendbuff));
    send(peerfd, sendbuff, strlen(sendbuff), 0);

    int flag = sendbuff[0] - '0';
    char salt[20] = {0};

    if(flag == 0)
    {
        printf("----请输入用户名----\n");
        read(STDIN_FILENO, recvbuff, sizeof(recvbuff));
        train.length = strlen(recvbuff);//用户名长度
        strcpy(train.buff, recvbuff);
        //这里有可能会把\n写进去，所以用小火车保险点，不容易出错
        send(peerfd, &train, 4 + train.length, 0);

        /*----接受盐值----*/
        int length = 0;
        recvCircle(peerfd, (char *)&length, 4);
        recvCircle(peerfd, salt,length);
        printf("接收的盐值为：%s\n", salt);//显示一下，防止出错

        /*----输入密码----*/
        char *passwd;
        passwd = getpass("请输入密码：");

        /*----合成密文并发送----*/
        char *cryptpasswd = crypt(passwd, salt);
        printf("合成的密文为：%s\n", cryptpasswd);//显示一下，防止出问题
        memset(&train, 0, sizeof(train));
        train.length = strlen(cryptpasswd);
        strcpy(train.buff, cryptpasswd);
        send(peerfd, &train, 4 + train.length, 0);

        memset(&recvbuff, 0, sizeof(recvbuff));
        recv(peerfd, recvbuff, sizeof(recvbuff), 0);
        puts(recvbuff);
        return 1;
    }
    else if(flag == 1) {
        printf("----请输入用户名----\n");
        read(STDIN_FILENO, recvbuff, sizeof(recvbuff));
        train.length = strlen(recvbuff);//用户名长度
        strcpy(train.buff, recvbuff);
        //这里有可能会把\n写进去，所以用小火车保险点，不容易出错
        send(peerfd, &train, 4 + train.length, 0);

        /*----接收盐值----*/
        int length = 0;
        recvCircle(peerfd, (char *)&length, 4);
        recvCircle(peerfd, salt,length);
        printf("接收的盐值为：%s\n", salt);//显示一下，防止出错

        /*----输入密码----*/
        char *passwd;
        passwd = getpass("请输入密码：");

        /*----形成密文并发送----*/
        char *cryptpasswd = crypt(passwd, salt);
        printf("合成的密文为：%s\n", cryptpasswd);//显示一下，防止出问题
        memset(&train, 0, sizeof(train));
        train.length = strlen(cryptpasswd);
        strcpy(train.buff, cryptpasswd);
        send(peerfd, &train, 4 + train.length, 0);

        memset(&recvbuff, 0, sizeof(recvbuff));
        recv(peerfd, recvbuff, sizeof(recvbuff), 0);
        puts(recvbuff);
        if(strcmp(recvbuff,"登录失败！请重新登陆！") == 0){
            return 1;
        }
        return 0;
    }
}
